/*
Learning from Law Enforcement
Libor Dusek and Christian Traxler

Do-file producing regression results and figures in the paper.

*************************************
*** 0. DESCRIPTION AND PRELIMINARIES
**************************************

*** The input datasets are 
	Dusek_Traxler_EVENT_weekeffects_100s (for estimating weekly effects)
	Dusek_Traxler_EVENT_montheffects_100s (for estimating monthly effects)
	They should be placed in a directory /Datasets
	
*** This do-file runs only with a complementary do-file, supportprograms.do, placed in the same directory. 
	(supportprograms.do define programs for drawing plots of estimated effects, etc.)
	
*** Outputs are placed in output directories outfiles/EVENT_TAB and EVENT_FIG
	Names of outpupt files correspond to the Table/Column/Figure numbers in the paper
*** Temporary files created in the process are placed in outfiles/EVENT_temp and erased while running the do-file
	
*** The do-file is separated into switches (e.g. sw01_basicbyseverity) that are listed on the lines 41-52. 
	To run a particular switch, set its value to 1. To turn it off (and save computing time), set to 0.

*** The do-file runs on Stata 14 or higher

*** The following Stata packages need to be installed:
	estout/eststo
	ftools
	labutil
	outreg2
	panelstat
	parmest
	ranktest
	reghdfe
	
	
*** List of Figures and Tables in the paper and the corresponding switches:
Fig 5    - sw01
Fig 6    - sw02
Fig 7    - sw51
Fig A.12 - sw06
Fig A.13 - sw05
Fig A.14 - sw03
Fig A.15 - sw03
Fig A.16 - sw03
Fig A.17 - sw04
Fig A.18 - sw09
Fig D.1  - sw08
Table A.1 - ??? Full sample, originally in do-file dor29 (??? Bring it here??) LD ASK
- > needs separate file and dataset
- do transform, keep and generate the table
Table A.10, cols 1-4 - sw01, cols 5-8 - sw03
Table A.11, cols 1-2 - sw51, cols 3-4 - sw38
Table A.12 - sw03
Table A.13, cols 1-4 - sw04 , cols 5-6 - sw09
Table D.1 - sw08
Table D.2 - sw08
*/

*************************************
*** 1.SETTINGS
*************************************
*** Do-file settings
set trace off
clear
set scrollbufsize 300000
set more off
set matsize 1200
set emptycells drop
capture log close
do supportprograms

*** DEFINE SWITCHES
***** ESTIMATING WEEKLY EFFECTS
local sw01_basicbyseverity =	1	// Figures 5, Tables A.10 (cols 1-4)
local sw02_regsheterog  = 		1  // Figure 6
local sw03_heterogbyseverity 	= 1  	// Figures A.14, A.15, A.16, Tables A.10 (cols 5-8), A.12
local sw04_off2tkt1    			= 1	// Figure  A.17, Table A.13 (cols 1-4)
local sw05_regsdrivenobyseverity = 1	// Figure A.13, Table A.11 (col 3-4)
local sw06_rddbyseverity = 1		// Figure A.12
local sw07_plotsbyseverity 		= 1   	// Figure D.1
local sw08_robchecksampleBE = 1			// Tables D.1, D.2
local sw09_2ndadditional = 1 			// Figure A.18, Table A.13 (col. 5-6)
***** ESTIMATING MONTHLY EFFECTS
local sw51_regsbasic = 1		// Figure 7, Table A.11 (col. 1,2)


*** Set directories: 
* Working directory (individual setting: this is the directory where the do-files are placed)
global dir C:/yourdir/
cd    $dir
* Data directory
global datadir $dir/datasets
* Output directories
global outputdir outfiles
capture mkdir ${outputdir}
capture mkdir ${outputdir}/EVENT_TAB
capture mkdir ${outputdir}/EVENT_FIG
capture mkdir ${outputdir}/EVENT_temp


*** POST/PRE WINDOWS
*** Set the length of the windows before/after tickets within which the 
*** effects are estiamted 
*** The windows are set as a parameter scalars
*** both as global macros (for dummy titles etc) and scalars (for computations)
 
** windows in terms of weeks: 
global prew "12"
global postw "20"
local prew = ${prew}
scalar prew =  ${prew}
local postw = ${postw}
scalar postw = ${postw}
* also need # of pre-weeks -1
scalar prew1 = prew - 1
local prew1 = `prew' - 1
global prew1 "`prew1'"

*** windows in terms of drive numbers:
global predrvn "75"
global postdrvn "100"
local predrvn = ${predrvn}
scalar predrvn =  ${predrvn}
local postdrvn = ${postdrvn}
scalar postdrvn = ${postdrvn}
* also need # of pre-drvneeks -1
scalar predrvn1 = predrvn - 1
local predrvn1 = `predrvn' - 1
global predrvn1 "`predrvn1'"

********************************************************
*** SWITCH 1
*** BASIC REGRESSIONS BY FINE SEVERITY, RESPONSES BY WEEKLY INTERVALS BEFORE/AFTER
*** Produces the following:
* Figure 5 (Event study estimates: responses to low-fine tickets: Speed, Speeding)
* Table A.10 cols 1-4 (Event analysis: responses to the first ticket: Speed, Speeding outcomes split by low fine/high fine ticket)	
********************************************************
if `sw01_basicbyseverity' == 1 {
	log using ${outputdir}/EVENT_TAB/01_log_eventpaper_basic, replace	
	**********************************************
	**** 1. REGRESSIONS - BASIC EVENT ANALYSIS AROUND THE TICKET
	**** Broken down by severity levels 1 and 2 
	************************************************	
	* Erase existing outfiles
	capture erase ${outputdir}/EVENT_TAB/TabA10_c1_c2_outreg_basicbyseverity_s1.txt
	capture erase ${outputdir}/EVENT_TAB/TabA10_c1_c2_outreg_basicbyseverity_s1.tex
	capture erase ${outputdir}/EVENT_TAB/TabA10_c3_c4_outreg_basicbyseverity_s2.txt
	capture erase ${outputdir}/EVENT_TAB/TabA10_c3_c4_outreg_basicbyseverity_s2.tex

	*** Loop by offense severity 
	forvalues s = 1/2 {
		*** Loop by the ticket order (only first ticket)
		forvalues i = 1/1 {		
			clear 
			use ${datadir}/Dusek_Traxler_EVENT_weekeffects
			*** For drawing graphs, rename the dummies indicating each week before/after each ticket
			scalar prew1 = prew -1 
			local prew1 = prew1
			forvalues j =  `prew1' (-1) 1  {
				rename dw_`j'_ticket`i' dw_`j'_reg
			}
			forvalues j = 0 (1) ${postw} {
				rename dw`j'_ticket`i' dw`j'_reg
			}
			save ${outputdir}/EVENT_temp/temp, replace
			
			* Define the lists of variables in the regressions
			* treatment dummies:
			global Tdumprelist "dw_${prew1}_reg-dw_1_reg"
			global Tdumpostlist "dw1_reg -dw${postw}_reg"

			* time, traffic, and weather controls: everyting radar-specific:
			global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Xlistmonth "radarid##dofweek radarid##hofday radarid##month radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

			*** General condition for the sample - time window and sampledriver:
			global samplecondition "trigsever`i'==`s' & weeks_ticket`i'>=-${prew1} & weeks_ticket`i'<=${postw} & oldthreshticket`i'==1 & sampledriver`i'==1"
			*** general options for outreg
			global outregspeeding "tex label dec(3)"
			global outregspeed    "tex label dec(2)"

			*** Text for the note 
			global addedtext_fe "car fe, yes, radar fe, yes, hofd/dofw/mofy fe, radar-spec, traffic controls, radar-spec"			

			** Set omitted categories for dummies
			* radar: //Ricanska-valley (the most frequent, and most violating)
			char radarid[omit] 5 
			* day of week: //Monday
			char dofweek[omit] 1 
			* hour of day: //7:00-7:59 am, morning rush hour
			char hofday[omit]  7
			* month of year: January (1st, slow traffic) 
			char mofyear[omit] 1 // January
			* schoolday: no school
			char schoolday[omit] 0 	
			* holiday: //no holiday
			char holiday[omit] 0 
			* time difference from car in front: 0-2 seconds (bumper-to-bumper)
			char timediffint[omit] 2 

			*********************************************************
			*** 1.1 OUTCOME: Speeding, pre-post dummies
			*****************************************************************
			*** before each reg, compute the mean of the outcome and store it for inclusion in the output table			
			display "Speeding after ticket, Severity = `s', Ticket order = `i'"
			display "Driver F.E., pre-and post-ticket dummies, excl. trigger obs"
			sum speeding if tkt_order~=`i' & trigsever`i'==`s' & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
			local pretreat0ex = round(r(mean), 0.001) 	
			
			*** name variables based on severity level to reflect titles in the paper
			if (`s'== 1) {
				local out_name_table = "TabA10_c1_c2_outreg_basicbyseverity_s1"				
				local out_name_coefplot1 = "Fig_5a_coefplot_speeding_excltrig_s1tkt`i'"
				local out_name_coefplot2 = "Fig_5b_coefplot_speed_excltrig_s1tkt`i'"
			} 
			else {				
				local out_name_table =  "TabA10_c3_c4_outreg_basicbyseverity_s2"		
			}		
			
			*** Table A.10 
			xi: reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)	
			outreg2 using ${outputdir}/EVENT_TAB/`out_name_table', ${outregspeeding} keep(dw*reg) ctitle(ticket`i', speeding) addtext(pre-ticket mean, `pretreat0ex', no. of cars, `e(N_clust)', ${addedtext_fe}, weather controls, yes) 
			// draw the coeff plot only for low severity
			if (`s'== 1) {
				
				*** Plotting the coefficients:
				*** first store the estimates into a temporary file
				parmest, saving(${outputdir}/EVENT_FIG/parms, replace)
				*** call in the program plotRegWeeks loaded from a do-file supportprograms.do	
			
				*** Figure 5a
				plotRegWeeks `out_name_coefplot1' "" "Probability of speeding" "" "Weeks before/after ticket `i'" ""
			}
			*********************************************************
			***  1.2 OUTCOME: Speed, pre-post dummies
			********************************************************************
			*** before each reg, compute the mean of the outcome and store it for inclusion in the output table			
			display "Rel speed after ticket, Severity = `s', Ticket order = `i'"
			display "Driver F.E., pre-and post-ticket dummies, excl. trigger obs"

			sum speedm if tkt_order~=`i' & trigsever`i'==`s' & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
			local pretreat0ex = round(r(mean), 0.001) 

			*** Table A.10 
			xi: reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)		
			outreg2 using ${outputdir}/EVENT_TAB/`out_name_table', ${outregspeeding} keep(dw*reg) ctitle(ticket`i', speed) addtext(pre-ticket mean, `pretreat0ex', no. of cars, `e(N_clust)', ${addedtext_fe}, weather controls, yes) 
			// draw the coeff plot only for low severity
			if (`s'== 1) {
				parmest, saving(${outputdir}/EVENT_FIG/parms, replace)
				
				*** Figure 5b
				plotRegWeeks `out_name_coefplot2' "" "Speed (km/h)" "" "Weeks before/after ticket `i'" ""		
			}
		}
		* end of loop over tickets
	} 
	* end of loop over severity levels
	cap erase temp.dta
	log close
}
* end sw01

****************************************************
*** SWITCH 2
*** REGRESSIONS - HETEROGENEITY OF RESPONSES
*** Produces the following:
*** Figure 6 (Event study estimates: responses to high- vs low-fine tickets)
****************************************************
if `sw02_regsheterog' == 1 {	
	log using ${outputdir}/EVENT_TAB/02_log_eventpaper_heterog, replace
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear	
	
	* Loop over ticket order (first ticket only)
	forvalues i = 1 / 1 {
		************************************************
		*** Preparing for regressions
		*************************************************
		*** Variable lists - analogous to sw01
		global Tdumprelist "dw_${prew1}_ticket`i'-dw_1_ticket`i'"
		global Tdumpostlist "dw1_ticket`i'-dw${postw}_ticket`i'"
		global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
		global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

		** outreg options, with different decimal points for different outcomes
		global outregspeeding "tex label dec(3) nocons"
		global outregspeed    "tex label dec(2)  nocons"
		global addedtext_fe "car fe, yes, radar fe, yes, hour/day/month fe, radar-spec, traffic controls, radar-spec, weather controls, yes"

		*** Sample condition
		global samplecondition "weeks_ticket`i'>=-prew1 & weeks_ticket`i'<=postw & oldthreshticket`i'==1 & sampledriver`i'==1"

		** Set omitted categories for dummies		
		* radar: //Ricanska-valley (the most frequent, and most violating)
		char radarid[omit] 5 
		* day of week: //Monday
		char dofweek[omit] 1 
		* hour of day: //7:00-7:59 am, morning rush hour
		char hofday[omit]  7
		* month of year: January (1st, slow traffic) 
		char mofyear[omit] 1 // January
		* schoolday: no school
		char schoolday[omit] 0 
		* holiday: //no holiday
		char holiday[omit] 0 
		* time difference from car in front: 0-2 seconds (bumper-to-bumper)
		char timediffint[omit] 2 

		*************************************
		*** 2.1 BY OFFENSE SEVERITY: SPEEDING
		************************************		
		*******************************************************************
		*** Collect outcome averages pre-ticket, by severity levels 1 and 2 
		******************************************************************
		* speeding, severity 1
		sum speeding if tkt_order~=`i' & trigsever`i'==1 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pt_speedingex`i'_severity1 = round(r(mean), 0.001)
		* speeding, severity 2
		sum speeding if tkt_order~=`i' & trigsever`i'==2 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pt_speedingex`i'_severity2 = round(r(mean), 0.001)
		* speeding, all
		sum speeding if tkt_order~=`i' & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pt_speedingex`i'_all = round(r(mean), 0.001)
		***************************************************
		*** Actual Regressions: speeding by offense severity
		***************************************************
		display "By offense severity (1, 2)"
		display "Response after the ticket"
		display "Outcome: speeding above the limit"

		* Figure 6a (same reg also in Table A.10 col 1)
		display "Speeding, severity 1, excl trigger obs"	
		reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & trigsever`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
		parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

		* JEEA Figure 6a (same reg also in Table A.10 col 3)
		display "Speeding, severity 2, excl trigger obs"	
		reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & trigsever`i'==2 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
		parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
		
		* Figure 6a
		* plotting the coefficients into a combined figure
		* calls in a program plot2RegsWeeks, defined in a do-file supportprograms
		plot2RegsWeeks "Fig_6a_coefplot_severity_speeding`i'" "Low fine" "High fine" "Probability of speeding" "" "Weeks before/after ticket `i'" ""	

		*************************************
		*** 2.2. BY OFFENSE SEVERITY: SPEED
		************************************

		*******************************************************************
		*** Collect outcome averages pre-ticket, by offense severity 1, 2 
		******************************************************************
		* relspeedm, severity 1, trigger obs excl
		sum speedm if tkt_order~=`i' & trigsever`i'==1 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pt_speedex`i'_severity1 = round(r(mean), 0.001)
		* relspeedm, severity 2, trigger exlc
		sum speedm if tkt_order~=`i' & trigsever`i'==2 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pt_speedex`i'_severity2 = round(r(mean), 0.001)
		* relspeedm, all, trigger excl
		sum speedm if tkt_order~=`i' & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pt_speedex`i'_all = round(r(mean), 0.001)

		***************************************************
		*** Actual Regressions: Speed by offense severity
		***************************************************
		display "By offense severity 1, 2"
		display "Response after the ticket"
		display "Outcome: relspeedm above the limit"

		* JEEA Figure 6b (same reg also in Table A.10 col 2)
		display "speed, severity 1, excl trigger obs"	
		reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & trigsever`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
		parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

		* JEEA Figure 6b (same reg also in Table A.10 col 4)
		display "speed, severity 2, excl trigger obs"	
		reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & trigsever`i'==2 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
		parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
		* JEEA Figure 6b
		* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
		
		plot2RegsWeeks "Fig_6b_coefplot_severity_speed`i'"  "Low fine" "High fine"  "Speed (km/h)" "" "Weeks before/after ticket `i'" ""
	}
	log close
}
* end sw02

****************************************************
*** SWITCH 3
*** REGRESSIONS - HETEROGENEITY OF RESPONSES
*** Produces the following:
*** Figure A.14 (Event study estimates: same vs other speed camera zones)
*** Figure A.15 (Event study estimates: private owner vs corporation)
*** Figure A.16 (Event study estimates: paid vs unpaid tickets)
*** Table A.10 cols 5-8 (Event analysis: responses to the first ticket: Speed, Speeding broken down by other/same zone)
*** Table A.12 (Event analysis: heterogeneity: Speed, Speeding by car owner and payment of ticket)
****************************************************
if `sw03_heterogbyseverity' == 1 {
	log using ${outputdir}/EVENT_TAB/03_log_eventpaper_heterog_byseverity, replace
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear
	* Loop over fine severity (low fines only)
	forvalues s = 1 / 1 {
		* Loop over ticket order (first ticket only)
		forvalues i = 1 / 1 {
			************************************************
			*** Preparing for regressions
			*************************************************
			*** Variable lists and options 
			global Tdumprelist "dw_${prew1}_ticket`i'-dw_1_ticket`i'"
			global Tdumpostlist "dw1_ticket`i'-dw${postw}_ticket`i'"
			global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

			** outreg options, with different decimal points for different outcomes
			global outregspeeding "tex label dec(3) nocons"
			global outregspeed    "tex label dec(2)  nocons"
			global addedtext_fe "car fe, yes, radar fe, yes, hour/day/month fe, radar-spec, traffic controls, radar-spec, weather controls, yes"
			** sample condition
			global samplecondition "trigsever`i' == `s' & weeks_ticket`i'>=-prew1 & weeks_ticket`i'<=postw & oldthreshticket`i'==1 & sampledriver`i'==1"

			** Set omitted categories for dummies		
			* radar: //Ricanska-valley (the most frequent, and most violating)
			char radarid[omit] 5 
			* day of week: //Monday
			char dofweek[omit] 1 
			* hour of day: //7:00-7:59 am, morning rush hour
			char hofday[omit]  7
			* month of year: January (1st, slow traffic) 
			char mofyear[omit] 1 // January
			* schoolday: no school
			char schoolday[omit] 0 
			* holiday: //no holiday
			char holiday[omit] 0 
			* time difference from car in front: 0-2 seconds (bumper-to-bumper)
			char timediffint[omit] 2 
			
			*************************************
			*** 3.1. By Private / Corporate
			*************************************
			
			*************************************
			*** 3.1.1. By Private / Corp: Speeding regressions 
			*************************************
			
			***  Erase outregfiles (these are used for other outcomes as well)
			capture erase ${outputdir}/EVENT_TAB/TabA12_corp_compare_c1_c2_c3_c4_s`s'tkt`i'.tex
			capture erase ${outputdir}/EVENT_TAB/TabA12_corp_compare_c1_c2_c3_c4_s`s'tkt`i'.txt
			
			*******************************************************************
			*** Collect outcome averages pre-ticket, by corporation and private
			******************************************************************
			* speeding, corp, trigger excl
			sum speeding if trigsever`i' == `s' & tkt_order~=`i' & dum_corp==1 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedingex`i'_corp = round(r(mean), 0.001)
			* speeding, private, trigger exlc
			sum speeding if trigsever`i' == `s' & tkt_order~=`i' & dum_corp==0 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedingex`i'_priv = round(r(mean), 0.001)
			
			***************************************************
			*** Actual Regressions: speeding by private/corporation
			***************************************************
			display "By private driver (0) / corporation (1)"
			display "Response after the ticket"
			display "Outcome: speeding above the limit"
			display "Severity `s'"

			*** JEEA Figure A.15a, Table A.12 col 1:
			display "speeding, Private driver, Excl trigger"	
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_corp==0 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c1_c2_c3_c4_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, private, severity `s') addtext(pre-ticket mean, `pt_speedingex`i'_priv', no. of cars, `e(N_clust)', ${addedtext_fe}) append

			* for plotting the coefficients, save the estimates which will then be merged with the estimates for the Corporation
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			*** Figure A.15a, Table A.12 col 2:
			display "Speeding, corporation, excl trigger"	
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_corp==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c1_c2_c3_c4_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, corporation, severity `s') addtext(pre-ticket mean, `pt_speedingex`i'_corp', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			
			*** Figure A.15a
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			plot2RegsWeeks "Fig_A15a_coefplot_corp_speeding_s`s'tkt`i'" "Private owner" "Corporation" "Probability of speeding" "" "Weeks before/after ticket `i'" ""

			**************************************************
			*** 3.1.2.  By Private / Corp: speed 
			**************************************************
			
			**************************************************
			*** Collect the means of the pre-treatment (all weeks before ticket)
			**************************************************
			* speed, corp, excl trigger
			sum speedm if tkt_order~=`i' & dum_corp==1 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedex`i'_corp = round(r(mean), 0.01)
			* speed, private, excl trigger
			sum speedm if tkt_order~=`i' & dum_corp==0 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedex`i'_priv = round(r(mean), 0.01)
				
			**************************************************
			*** Actual regressions: speed by private/corporation	
			**************************************************
			display "By private driver (0) / corporation (1)"
			display "Response after the ticket"
			display "Outcome: speed"

			***  Figure A.15b, Table A.12 col 3:
			display "Speed, private driver, exlc trigger"	
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_corp==0 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c1_c2_c3_c4_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeed} ctitle(speed, private, severity `s') addtext(pre-ticket mean, `pt_speedex`i'_priv', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			*** Figure A.15b, Table A.12 col 4:
			display "Speed, corporation, excl trigger"	
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_corp==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c1_c2_c3_c4_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeed} ctitle(speed, corporation, severity `s') addtext(pre-ticket mean, `pt_speedex`i'_corp', no. of cars, `e(N_clust)', ${addedtext_fe}) append

			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)

			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A15b_coefplot_corp_speed_s`s'tkt`i'" "Private owner" "Corporation" "Speed (km/h)" "" "Weeks before/after ticket `i'" ""

			*************************************
			*** 3.2. By whether ticket was paid or not
			*************************************
			
			********************************************************************	
			** 3.2.1. By whether ticket was paid or not: speeding
			*********************************************************************

			* Erase outreg files
			capture erase ${outputdir}/EVENT_TAB/TabA12_corp_compare_c5_c6_c7_c8_s`s'tkt`i'.tex
			capture erase ${outputdir}/EVENT_TAB/TabA12_corp_compare_c5_c6_c7_c8_s`s'tkt`i'.txt
			
			**************************************************
			*** Collect pre-ticket averages, by ticket paid/notpaid
			**************************************************
		
			* speeding, paid, trigger excl
			sum speeding if tkt_order~=`i' & dum_paid`i'==1 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedingex`i'_tktpaid = round(r(mean), 0.001)
			* speeding, not paid, trigger excl
			sum speeding if tkt_order~=`i' & dum_paid`i'==0 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedingex`i'_tktnotpaid = round(r(mean), 0.001)
		
			display "By whether the ticket was paid (1) within 90 days"
			display "Response after the ticket"
			display "Outcome: speeding above the limit"			
			
			**************************************************
			*** Actual regressions: by ticket paid/notpaid
			**************************************************
			* Figure A.16a, Table A.12 col 5
			display "Speeding, Ticket not paid (within 90 days), Excl trigger"
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if dum_paid`i'==0 & tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c5_c6_c7_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, ticket not paid, severity `s') addtext(pre-ticket mean, `pt_speedingex`i'_tktnotpaid', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			* Figure A.16a, Table A.12 col 6
			display "Speeding, Ticket paid (within 90 days), excl trigger"
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if dum_paid`i'==1 & tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c5_c6_c7_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, ticket paid, severity `s') addtext(pre-ticket mean, `pt_speedingex`i'_tktpaid', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			* Figure A.16a
			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A16a_coefplot_tktpaid_speeding_s`s'tkt`i'" "Ticket not paid" "Ticket paid" "Probability of speeding" "" "Weeks before/after ticket `i'" ""


			********************************************************************	
			** 3.2.1 By whether ticket was paid or not: speed
			*********************************************************************
			
			**************************************************
			*** Collect pre-ticket averages, by ticket paid/notpaid
			**************************************************
			* speed, paid, trigger excl
			sum speedm if tkt_order~=`i' & dum_paid`i'==1 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedex`i'_tktpaid = round(r(mean), 0.001)
			* speed, not paid, trigger excl
			sum speedm if tkt_order~=`i' & dum_paid`i'==0 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedex`i'_tktnotpaid = round(r(mean), 0.001)
			
			**************************************************
			*** Actual regressions: speed by ticket paid/not paid
			**************************************************
			display "By whether the ticket was paid (1) within 90 days"
			display "Response after the ticket"
			display "Outcome: speed rel. to the limit"

			* Figure A.16b, Table A.12 col 7
			display "Speed, Ticket not paid (within 90 days), Excl trigger"
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if dum_paid`i'==0 & tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c5_c6_c7_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeed} ctitle(speed, ticket not paid, severity `s') addtext(pre-ticket mean, `pt_speedex`i'_tktnotpaid', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			* Figure A.16b, Table A.12 col 8
			display "Speed, Ticket paid (within 90 days), excl trigger"
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if dum_paid`i'==1 & tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA12_corp_compare_c5_c6_c7_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeed} ctitle(speed, ticket paid, severity `s') addtext(pre-ticket mean, `pt_speedex`i'_tktpaid', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			* Figure A.16b
			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A16b_coefplot_tktpaid_speed_s`s'tkt`i'" "Ticket not paid" "Ticket paid" "Speed (km/h)" "" "Weeks before/after ticket `i'" ""

			*************************************
			*** 3.3. BY SAME ZONE AND OTHER ZONES
			*************************************	
			
			*************************************
			*** 3.3.1. BY SAME ZONE AND OTHER ZONES: SPEEDING
			************************************
			capture erase ${outputdir}/EVENT_TAB/TabA10_zones_compare_c5_c7_c6_c8_s`s'tkt`i'.tex
			capture erase ${outputdir}/EVENT_TAB/TabA10_zones_compare_c5_c7_c6_c8_s`s'tkt`i'.txt
			*******************************************************************
			***  Collect outcome averages pre-ticket, by trigger and other radars
			******************************************************************
			* speeding, same (trigger) zone, trigger obs excluded
			sum speeding if tkt_order~=`i' & dum_trigrad`i'==1 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedingex`i'_trigrad = round(r(mean), 0.001)
			* speeding, other zones, trigger obs exlcluded
			sum speeding if tkt_order~=`i' & dum_trigrad`i'==0 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedingex`i'_othrad = round(r(mean), 0.001)
			
			***************************************************
			*** Actual Regressions: speeding by trigger radars/other radars
			***************************************************
			display "By trigger radar (1) / other radars (0)"
			display "Response after the ticket"
			display "Outcome: speeding above the limit"

			* Figure A.14a, Table A.10 col 5:
			display "Speeding, trigger radar, excl trigger obs"	
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_trigrad`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA10_zones_compare_c5_c7_c6_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, trigger radar, severity `s') addtext(pre-ticket mean, `pt_speedingex`i'_trigrad', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			* JEEA Figure A.14a, Table A.10 col 7:
			display "Speeding, other radars, excl trigger obs"	
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_trigrad`i'==0 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA10_zones_compare_c5_c7_c6_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, other radars, severity `s') addtext(pre-ticket mean, `pt_speedingex`i'_othrad', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			* Figure A.14a
			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A14a_coefplot_trigrad_speeding_s`s'tkt`i'" "Same zone" "Other zones" "Probability of speeding" "" "Weeks before/after ticket `i'" ""

			*************************************
			*** 3.3.2. BY TRIGGER AND OTHER RADARS: SPEED
			************************************

			*******************************************************************
			*** Collect outcome averages pre-ticket, by trigger and other radars
			******************************************************************
			* relspeedm, trigger radar, trigger obs excl
			sum speedm if tkt_order~=`i' & dum_trigrad`i'==1 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedex`i'_trigrad = round(r(mean), 0.001)
			* relspeedm, other radars, trigger exlc
			sum speedm if tkt_order~=`i' & dum_trigrad`i'==0 & weeks_ticket`i'==0 & ${samplecondition}
			local pt_speedex`i'_othrad = round(r(mean), 0.001)
			
			***************************************************
			*** Actual Regressions: Speed by trigger radars/other radars
			***************************************************
			display "By trigger radar (1) / other radars (0)"
			display "Response after the ticket"
			display "Outcome: relspeedm above the limit"

			* JEEA Figure A.14b, Table A.10 col 6:
			display "speed, trigger radar, excl trigger obs"	
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_trigrad`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA10_zones_compare_c5_c7_c6_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speed, trigger radar, severity `s') addtext(pre-ticket mean, `pt_speedex`i'_trigrad', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			* JEEA Figure A.14b, Table A.10 col 8:
			display "speed, other radars, excl trigger obs"	
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & dum_trigrad`i'==0 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA10_zones_compare_c5_c7_c6_c8_s`s'tkt`i', drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speed, other radars, severity `s') addtext(pre-ticket mean, `pt_speedex`i'_othrad', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			* JEEA Figure A.14b
			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A14b_coefplot_trigrad_speed_s`s'tkt`i'"  "Same zone" "Other zones"  "Speed (km/h)" "" "Weeks before/after ticket `i'" ""

		}
		* end loop over ticket number

	}
	* end loop over severity level

	log close
}
* end sw03

************************************************
**** Switch 04
**** HETEROGENEITY WITHIN THE FIRST TICKET BY WHETHER A CAR RECEIVED A SECOND TICKET
**** FURTHER BROKEN DOWN BY SEVERITY
*** Produces the following: 
**** Figure A.17 (Event study estimates by re-offence pattern)
**** Table A.13 cols 1-4 (vent analysis: reoffending status and second ticket)
*************************************************
if `sw04_off2tkt1' == 1 {
	log using ${outputdir}/EVENT_TAB/04_log_off2tkt1, replace
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects
	**********************************************
	**** REGRESSIONS - RESPONSE TO 1ST TICKET BY WHETHER RECIEVIED 2ND TICKET
	**** FURTHER BROKEN DOWN BY WHETHER THE FIRST TICKET WAS OF LOW OR HIGH SEVERITY
	************************************************
	*** Loop over fine severity
	forvalues s = 1/1 {
		*** For programming consistency, run it as a loop over tickets, but in fact run just over one ticket 
		forvalues i = 1/1 {
			***********************************
			*** Preparing the regressions
			***********************************
			*** List of treatment dummies in the order we want it, with week zero as ommitted category
			global Tdumprelist "dw_${prew1}_ticket`i'-dw_1_ticket`i'"
			global Tdumpostlist "dw1_ticket`i'-dw${postw}_ticket`i'"

			* time and traffic controls: everyting radar-specific
			global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

			*** General condition for the sample - time window and sampledriver
			global samplecondition "trigsever`i'==`s' & weeks_ticket`i'>=-${prew1} & weeks_ticket`i'<=${postw} & oldthreshticket`i'==1 & sampledriver`i'==1"
			*** general options for outreg
			global outregspeeding "tex label dec(3) drop(_I*)"
			global outregspeed    "tex label dec(2) drop(_I*)"
			*** Text for the note - different for regs without/with driver f.e.
			global addedtext_fe "car fe, yes, zone fe, yes, hofd/dofw/mofy fe, zone-spec, traffic controls, zone-spec, weather controls, yes"

			** Set omitted categories for dummies
			* radar: //Ricanska-valley (the most frequent, and most violating)
			char radarid[omit] 5 
			* day of week: //Monday
			char dofweek[omit] 1 
			* hour of day: //7:00-7:59 am, morning rush hour
			char hofday[omit]  7
			* month of year: January (1st, slow traffic) 
			char mofyear[omit] 1 // January
			* schoolday: no school
			char schoolday[omit] 0 
			* holiday: //no holiday
			char holiday[omit] 0 
			* time difference from car in front: 0-2 seconds (bumper-to-bumper)
			char timediffint[omit] 2 

			*** Median of this value for those who committed the 2nd offense after 1st ticket and not between 1st offense and ticket)
			sum gap_offatkt1 if ${samplecondition} & d_offafter_tkt1~=. & d_offafter_tkt1==d_offafter_off1  & tkt_order==`i', detail
			display "The mean gap bw 2nd offense and tkt1 is: "
			display r(p50)
			scalar medgap = r(p50)

			*** Three groups: 
			*** 1. reoffended after 1st offense for the 1st time after 1st ticket, small gap from 1st ticket
			*** 2. reoffended after 1st offense for the 1st time after 1st ticket, large gap from 1st ticket
			*** 3. never offended after 1st offense
			*** Note: at the end, in the regressions, the cars are classified as
			*** Did not reoffend = group 3
			*** Reoffended = groups 1 and 2

			*** define the criteria for these groups (other than the general sample conditi
			* groups 1 and 2: technically: day when offended first after 1st ticket is the same as offending first after 1st offense
			global group1 "d_offafter_tkt1~=. & d_offafter_tkt1==d_offafter_off1 & gap_offatkt1<=medgap"
			global group2 "d_offafter_tkt1~=. & d_offafter_tkt1==d_offafter_off1 & gap_offatkt1>medgap"
			global group3 "d_offafter_off1==."

			*****************************************************************
			*** RESPONSE TO 1ST TICKET BY SUBSEQUENT OFFENDING AFTER OFFENSE 1 AND TICKET 1
			*** BY REOFFENDERS AND NON-REOFFENDERS (GROUPS 1+2 AND 3)
			*****************************************************************
			* Erase outfiles: 
			capture erase ${outputdir}/EVENT_TAB/TabA13_by2off_g2s_c1_c3_c2_c4_`s'tkt`i'.txt
			capture erase ${outputdir}/EVENT_TAB/TabA13_by2off_g2s_c1_c3_c2_c4_`s'tkt`i'.tex

			*************************************************************
			*** Regressions: speeding by subsequent 2nd offense
			*** groups 1+2 together against 3
			*************************************************************

			*** All regressions exclude the trigger obs
			* Collect pre-ticket averages, by groups 1+2 and 3 
			sum speeding if tkt_order~=`i' & weeks_ticket`i'==0 & (${group1} | ${group2}) & ${samplecondition} 
			local pt_speeding_g12 = round(r(mean), 0.001)
			sum speeding if tkt_order~=`i' & weeks_ticket`i'==0 & ${group3} & ${samplecondition} 
			local pt_speeding_g3 = round(r(mean), 0.001)

			display "By groups defined by re-offending after the 1st offense/ticket"
			display "Response after the 1st ticket"
			display "Outcome: speeding above the limit"
			display "Speeding, Did not reoffend = group3"
			
			*** Figure A.17a and Table A.13 col 1
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if ${group3} & tkt_order~=`i' & ${samplecondition}, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA13_by2off_g2s_c1_c3_c2_c4_`s'tkt`i', ${outregspeeding} ctitle(speeding, never reoff, severity `s') addtext(pre-ticket mean, `pt_speeding_g3', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			* store estimates for plotting
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			*** Figure A.17a and Table A.13 col 3
			display "Speeding, Reofended = groups 1 and 2 "
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if (${group1} | ${group2}) & tkt_order~=`i' & ${samplecondition}, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA13_by2off_g2s_c1_c3_c2_c4_`s'tkt`i', ${outregspeeding} ctitle(speeding, reoffended, severity `s') addtext(pre-ticket mean, `pt_speeding_g12', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			* store estimates for plotting
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			** *** Figure A.17a 
			** plot the coefficients into one graph (with / without CI)
			plot2RegsWeeks "Fig_A17a_coefplot_by2off_speeding_g2s`s'tkt`i'" "Did not reoffend" "Reoffended" "Probability of speeding" "" "Weeks before/after ticket `i'" ""

			************************************************************	
			*** Regressions: speed by subsequent 2nd offense
			*** groups 1+2 together against 3
			************************************************************

			*** All regressions exclude the trigger obs
			* Collect pre-ticket averages, by groups 1+2 and 3
			sum speedm if tkt_order~=`i' & weeks_ticket`i'==0 & (${group1} | ${group2}) & ${samplecondition} 
			local pt_speedm_g12 = round(r(mean), 0.001)
			sum speedm if tkt_order~=`i' & weeks_ticket`i'==0 & ${group3} & ${samplecondition} 
			local pt_speedm_g3 = round(r(mean), 0.001)

			display "By groups defined by re-offending after the 1st offense/ticket"
			display "Response after the 1st ticket"
			display "Outcome: speeding above the limit"

			display "Speed, Did not reoffend = group3"
			*** Figure A.17b and Table A.13 col 2
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if ${group3} & tkt_order~=`i' & ${samplecondition}, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA13_by2off_g2s_c1_c3_c2_c4_`s'tkt`i', ${outregspeed} ctitle(speed, never reoff, severity `s') addtext(pre-ticket mean, `pt_speedm_g3', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			* store estimates for plotting
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			display "Speed, Reoffended = groups 1+2"
			*** Figure A.17b and Table A.13 col 4
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if (${group1} | ${group2}) & tkt_order~=`i' & ${samplecondition}, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA13_by2off_g2s_c1_c3_c2_c4_`s'tkt`i', ${outregspeed} ctitle(speed, reoffended, severity `s') addtext(pre-ticket mean, `pt_speedm_g12', no. of cars, `e(N_clust)', ${addedtext_fe}) append
			* store estimates for plotting
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			*** Figure A.17b
			** plot the coefficients into one graph (with / without CI)
			plot2RegsWeeks "Fig_A17b_coefplot_by2off_speed_g2s`s'tkt`i'" "Did not reoffend" "Reoffended" "Speed (km/h)" "" "Weeks before/after ticket `i'" ""
			
		}
		* end ``loop'' over ticket 1/1
	} 
	* end loop over fine severity
	log close
}
* end switch 04

*************************************************************************
**** Switch 5
**** EVENT STUDY REGRESSIONS - EFFECTS DEFINED BY THE NUMBER OF RIDES BEFORE/AFTER TICKET
**** Produces the following: 
**** Figure A.13 (Event study estimates by ride sequence)
**** Table A.11, col 3-4 (Event analysis: long-run effects, analysis by the order of rides: order of the ride effect on speeding/speed )
*************************************************************************
if `sw05_regsdrivenobyseverity' == 1 {
	log using ${outputdir}/EVENT_TAB/05_log_driveno_basic_byseverity, replace
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear
	**********************************************
	*** 5. EVENT STUDY REGRESSIONS - EFFECTS DEFINED BY THE NUMBER OF RIDES BEFORE/AFTER TICKET
	************************************************

	*** Loop over offense severity (only low-fine actually used)

	forvalues s = 1 / 1 { 
		*** Outfiles: speeding and speed in one outfile for both tickets, separate for regs incl/excl trigger
		*** Then all regs for violation
		capture erase ${outputdir}/EVENT_TAB/TabA11_dn_excltrig_monthfe_c3_c4_s`s'.tex
		capture erase ${outputdir}/EVENT_TAB/TabA11_dn_excltrig_monthfe_c3_c4_s`s'.txt	

		*** loop by the ticket order
		forvalues i = 1/1 {
			**************************************
			***  Preparing the variables
			**************************************
			*** treatment dummies: 
			*** Rename it such that it is the same for ticket 1 and 2, and thus the outreg command
			*** puts the coefs on the same line for the ticket 1 and 2
			rename drvn5_ticket`i' drvn5_reg
			*** List of dummies for each 5 drive-throughs around the ticket
			global Tdrvn5list "io1000.drvn5_reg"

			* time and traffic controls: everything radar-specific
			global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Xlistmonth "radarid##dofweek radarid##hofday radarid##month radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"
			*** General condition for the sample - sampledriver (in terms of drives) and drive-throughs 
			global samplecondition "trigsever`i'==`s' & drive_no`i'>=-`predrvn' & drive_no`i'<=`postdrvn' & oldthreshticket`i'==1 & sampleno`i'==1"
			*** general options for outreg
			global outregspeeding "tex label dec(3) keep(i.drvn5_reg)"
			global outregspeed    "tex label dec(2) keep(i.drvn5_reg)"

			*** Text for the note  with driver f.e.
			global addedtext_fe "car fe, yes, radar fe, yes, hofd/dofw/mofy fe, radar-spec, traffic controls, radar-spec"
			
			** Set omitted categories for dummies
			* radar: //Ricanska-valley (the most frequent, and most violating)
			char radarid[omit] 5 
			* drive-through 5 intervals: drives -1 to -5 (takes value of 1000)
			char drvn5_reg[omit] 1000
			* day of week: //Monday
			char dofweek[omit] 1 
			* hour of day: //7:00-7:59 am, morning rush hour
			char hofday[omit]  7
			* month of year: January (1st, slow traffic) 
			char mofyear[omit] 1 // January
			* schoolday: no school
			char schoolday[omit] 0 
			* holiday: //no holiday
			char holiday[omit] 0 
			* time difference from car in front: 0-2 seconds (bumper-to-bumper)
			char timediffint[omit] 2 
			
			***************************************************************
			*** 5.2. Regressions: speeding
			***************************************************************		
			*** Regressions, exclude the trigger:
			* mean drive before (omitted category)
			sum speeding if drvn5_reg==1000 & tkt_order~=`i' & oldthreshticket`i'==1 & sampleno`i'==1 & trigsever`i'==`s'
			local pretreatex = round(r(mean), 0.001) 

			display "Speeding after ticket, ticket order = `i', severity `s'"
			display "excl trigger, calendar month dummies"

			*** Figure A.13a, Table A.11 col 3
			reghdfe speeding ${Tdrvn5list} ${Xlistmonth} ${Wlist} if tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 using ${outputdir}/EVENT_TAB/TabA11_dn_excltrig_monthfe_c3_c4_s`s', ${outregspeeding} ctitle(severity `s', ticket `i', speeding, excl trigger, cal month fe) addtext(pre-ticket mean, `pretreatex', no. of cars, `e(N_clust)', ${addedtext_femonth}) append
			
			*** Figure A.13a - plot the coeffs
			parmest, saving(${outputdir}/EVENT_FIG/parms, replace)	
			plotRegDrives `"Fig_A13a_coefplot_drvn_speeding_monthfe_s`s'tkt`i'"' "" `""' "probability of speeding" `"drive-throughs before/after ticket `i'"' ""


			**************************************************
			**** 5.3 Regressions: Speed
			**************************************************		
			*** Regressions with drive-through number dummies, exclude the trigger:
			* mean drive before (omitted category)
			sum relspeedm if drvn5_reg==1000 & tkt_order~=`i' & oldthreshticket`i'==1 & sampleno`i'==1 & trigsever`i'==`s'
			local pretreatex = round(r(mean), 0.001) 

			display "speed after ticket, ticket order = `i', severity `s'"
			display "excl trigger, calendar month dummies"

			*** Figure A.13b, Table A.11 col 4
			reghdfe relspeedm ${Tdrvn5list} ${Xlistmonth} ${Wlist} if tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 using ${outputdir}/EVENT_TAB/TabA11_dn_excltrig_monthfe_c3_c4_s`s', ${outregspeed} ctitle(severity `s', ticket `i', speed, excl trigger, cal month fe) addtext(pre-ticket mean, `pretreatex', no. of cars, `e(N_clust)', ${addedtext_femonth}) append

			*** Figure A.13b - plot the coeffs
			parmest, saving(${outputdir}/EVENT_FIG/parms, replace)	
			plotRegDrives `"Fig_A13b_coefplot_drvn_speed_monthfe_s`s'tkt`i'"' "" `""' "speed (km/h)" `"drive-throughs before/after ticket `i'"' ""

			* rename the treatment variable back
			rename drvn5_reg drvn5_ticket`i'
			save ${datadir}/Dusek_Traxler_EVENT_weekeffects, replace

		}
		* end loop over ticket number
	}
	* end loop over severity level

	log close
}
* end switch 05

****************************************************
*** Switch 6
*** REGRESSIONS - SAMPLE RESTRICTED TO NARROW BANDS AROUND THE HIGH-FINE CUTOFF (aka `RDD')
*** Produces the following: 
*** Figure A.12 (Event study estimates: responses to high- vs low-fine tickets – constrained sample)
****************************************************
if `sw06_rddbyseverity' == 1 {
	log using ${outputdir}/EVENT_TAB/06_log_rddbyseverity, replace
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear

	****************************************************
	***  REGRESSIONS - ESTIMATES BY OFFENSE SEVERITY 
	*** SAMPLE RESTRICTED TO NARROW BANDS AROUND THE HIGH-FINE CUTOFF (aka `RDD')	
	****************************************************
	forvalues i = 1 / 1 {
		************************************************
		*** Preparing for regressions
		*************************************************

		*** Variable lists and options - same as in 3
		global Tdumprelist "dw_${prew1}_ticket`i'-dw_1_ticket`i'"
		global Tdumpostlist "dw1_ticket`i'-dw${postw}_ticket`i'"
	
		global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
		global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"


		** outreg options, with different decimal points for different outcomes
		global outregspeeding "tex label dec(3) nocons"
		global outregspeed    "tex label dec(2)  nocons"
		global addedtext_fe "car fe, yes, radar fe, yes, hour/day/month fe, radar-spec, traffic controls, radar-spec, weather controls, yes"

		** General sample condition (the bandwidths around the cutoff are defined further below)
		global samplecondition "weeks_ticket`i'>=-prew1 & weeks_ticket`i'<=postw & oldthreshticket`i'==1 & sampledriver`i'==1"

		** Set omitted categories for dummies	
		* radar: //Ricanska-valley (the most frequent, and most violating)
		char radarid[omit] 5 
		* day of week: //Monday
		char dofweek[omit] 1 
		* hour of day: //7:00-7:59 am, morning rush hour
		char hofday[omit]  7
		* month of year: January (1st, slow traffic) 
		char mofyear[omit] 1 // January
		* schoolday: no school
		char schoolday[omit] 0 
		* holiday: //no holiday
		char holiday[omit] 0 
		* time difference from car in front: 0-2 seconds (bumper-to-bumper)
		char timediffint[omit] 2 

		*** Bandwidths around the cut-off:
		*** Band 1: optimal bandwith from RDD speeding regression, ride-level = 3.346
		local b1 = 3.346
		global band1 "(trigspeed`i' >= 23 - `b1' & trigspeed`i' <=23 + `b1')"

		*** Note: We also tried an alternative bandwidth 2 (results not meaningfully different)
		*** Band 2: optimal bandwith from RDD speed    regression, ride-level = 2.844
		*local b2 = 2.844
		*global band2 "(trigspeed`i' >= 23 - `b2' & trigspeed`i' <=23 + `b2')"

		*************************************
		*** BY SEVERITY LEVEL: SPEEDING
		************************************
		*** Erase outregfiles 
		capture erase ${outputdir}/EVENT_TAB/outreg_Fig_A12a.tex
		capture erase ${outputdir}/EVENT_TAB/outreg_Fig_A12a.txt

		* Loop over the bandwidths (band 1 only used in the paper)
		forvalues b = 1 (1) 1 {

			*******************************************************************
			*** Collect outcome averages pre-ticket, by severity levels 1 and 2 
			******************************************************************
			* speeding, severity 1, trigger excl
			sum speeding if ${band`b'} & tkt_order~=`i' & trigsever`i'==1 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
			local pt_speedingex`i'_severity1 = round(r(mean), 0.001)
			* speeding, severity 2, trigger exlc
			sum speeding if ${band`b'} & tkt_order~=`i' & trigsever`i'==2 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
			local pt_speedingex`i'_severity2 = round(r(mean), 0.001)

			***************************************************
			*** Actual Regressions: speeding by offense severity
			***************************************************
			display "By offense severity (1, 2)"
			display "Bandwidth `b'"
			display "Response after the ticket"
			display "Outcome: speeding above the limit"

			* Figure A.12a
			* Coefficients not reported in a table in the paper, here saved in outreg_Fig_A12a
			display "Speeding, severity 1, band`b'"	
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if ${band`b'} & tkt_order~=`i' & trigsever`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/outreg_Fig_A12a, drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, severity 1, band`b') addtext(pre-ticket mean, `pt_speedingex`i'_severity1', no. of cars, `e(N_clust1)', bandwidth, `b`b'', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)

			* Figure A.12a	
			display "Speeding, severity 2, band`b'"	
			reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if ${band`b'} & tkt_order~=`i' & trigsever`i'==2 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/outreg_Fig_A12a, drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speeding, severity 2, band`b') addtext(pre-ticket mean, `pt_speedingex`i'_severity2', no. of cars, `e(N_clust1)', bandwidth, `b`b'', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)
			
			* Figure A.12a	
			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A12a_coefplot_severity_speeding`i'_band`b'" "Low fine" "High fine" "Probability of speeding" "" "Weeks before/after ticket `i'" ""	

		}
		* end loop over bands


		*************************************
		*** BY OFFENSE SEVERITY: SPEED
		************************************

		*** Erase outfiles
		capture erase ${outputdir}/EVENT_TAB/outreg_Fig_A12b.tex
		capture erase ${outputdir}/EVENT_TAB/outreg_Fig_A12b.txt

		*** Loop over bandwidths
		forvalues b = 1 (1) 1 {

			*******************************************************************
			*** Collect outcome averages pre-ticket, by offense severity 1, 2 
			******************************************************************
			* relspeedm, severity 1, trigger obs excl
			sum speedm if ${band`b'} & tkt_order~=`i' & trigsever`i'==1 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
			local pt_speedex`i'_severity1 = round(r(mean), 0.001)
			* relspeedm, severity 2, trigger exlc
			sum speedm if ${band`b'} & tkt_order~=`i' & trigsever`i'==2 & weeks_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
			local pt_speedex`i'_severity2 = round(r(mean), 0.001)

			***************************************************
			*** Actual Regressions: Speed by offense severity
			***************************************************
			display "By offense severity 1, 2"
			display "Bandwidth `b'"
			display "Response after the ticket"
			display "Outcome: relspeedm above the limit"

			* Figure A.12b
			* Coeffs not reported in a table in the paper, here save in outreg_Fig_A12b
			display "speed, severity 1, band`b', excl trigger obs"	
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if ${band`b'} & tkt_order~=`i' & trigsever`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/outreg_Fig_A12b, drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speed, severity 1, band`b') addtext(pre-ticket mean, `pt_speedex`i'_severity1', no. of cars, `e(N_clust1)', bandwidth, `b`b'', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat1, replace)
			* Figure A.12b
			display "speed, severity 2, band`b', excl trigger obs"	
			reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if ${band`b'} & tkt_order~=`i' & trigsever`i'==2 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
			outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/outreg_Fig_A12b, drop(${Xlist} ${Wlist}) ${outregspeeding} ctitle(speed, severity 2, band`b') addtext(pre-ticket mean, `pt_speedex`i'_severity2', no. of cars, `e(N_clust1)', bandwidth, `b`b'', ${addedtext_fe}) append
			parmest, saving(${outputdir}/EVENT_FIG/parms_cat2, replace)

			* Figure A.12b
			* plotting the coefficients: calls in a program plot2RegsWeeks, defined in a do-file supportprograms
			plot2RegsWeeks "Fig_A12b_coefplot_severity_speed`i'_band`b'"  "Low fine" "High fine"  "Speed (km/h)" "" "Weeks before/after ticket `i'" ""

		}
		* end loop over b

	}
	* end loop over i


	log close
}
* end sw06

****************************************************
*** Switch 7
*** DESCRIPTIVE PLOTS BY WEEKS BEFORE/AFTER TICKET AND BY FINE SEVERITY
*** Produces the following: 
*** Figure D.1 (Event study: plot of raw data)
****************************************************
if `sw07_plotsbyseverity' == 1 {
	***********************************************************
	*** DESCRIPTIVE PLOTS BY WEEKS BEFORE/AFTER TICKET AND BY FINE SEVERITY:
	***********************************************************
	*** Load data
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear

	*** Aggregate stats by weeks before/after tickets: 
	*** Loop over tickets (here, only 1st ticket)
	forvalues i = 1/1 {
		*** Loop over fine severity
		forvalues s = 1/1 {
			*** 32.1.3 Speeding measures
			*** all are defined under the old enforcement threshold (valid till Oct 2017)
			*** Only for the drivers to be included in the sample (sample drivers)
			** avg speed
			bysort weeks_ticket`i': egen aweek_s`s'tkt`i'_speed = mean(relspeedm) if trigsever`i'==`s' & oldthreshticket`i'==1 & sampledriver`i'==1
			*** avgspeed - exclude the trigger observation
			*** the trigger observation is marked by the ticket number
			bysort weeks_ticket`i': egen xaweek_s`s'tkt`i'_speedex = mean(relspeedm) if trigsever`i'==`s' & oldthreshticket`i'==1 & tkt_order~=`i'  & sampledriver`i'==1
			bysort weeks_ticket`i': egen aweek_s`s'tkt`i'_speedex = max(xaweek_s`s'tkt`i'_speedex) if trigsever`i'==`s' & oldthreshticket`i'==1  & sampledriver`i'==1
			drop xaweek_s`s'tkt`i'_speedex

			*** rate of speeding (drive-throughs above the limit)
			bysort weeks_ticket`i': egen aweek_s`s'tkt`i'_fspeeding = mean(speeding) if trigsever`i'==`s' & oldthreshticket`i'==1  & sampledriver`i'==1
			*** rate of speeding - exclude the trigger osbervation
			bysort weeks_ticket`i': egen xaweek_s`s'tkt`i'_fspeedingex = mean(speeding) if trigsever`i'==`s' & oldthreshticket`i'==1 & tkt_order~=`i' & sampledriver`i'==1
			bysort weeks_ticket`i': egen aweek_s`s'tkt`i'_fspeedingex = max(xaweek_s`s'tkt`i'_fspeedingex) if trigsever`i'==`s' & oldthreshticket`i'==1 & sampledriver`i'==1
			drop xaweek_s`s'tkt`i'_fspeedingex

			*** 32.1.4 Sample size measures by the weeks before/after tickets

			*** 32.1.5. Label these variables
			label var aweek_s`s'tkt`i'_speed  "avg speed, by weeks b/a ticket `i'"
			label var aweek_s`s'tkt`i'_speedex "avg speed, exlc the trigger obs , by weeks b/a ticket `i'"

			label var aweek_s`s'tkt`i'_fspeeding   "rate of speeding above limit, by weeks b/a ticket `i'"
			label var aweek_s`s'tkt`i'_fspeedingex "rate of speeding above limit, excl the trigger obs, by weeks b/a ticket `i'"

		}
		* end loop over severity
	}
	* end loop over tickets

	save ${outputdir}/EVENT_temp/temp_aweek_s, replace

	******************************************************
	**** PLOTS - COLLAPSE THE DATA BY WEEKS AROUND THE TICKET
	******************************************************

	*** Loop over tickets (here, only 1st ticket)
	forvalues i = 1/1 {
		use ${outputdir}/EVENT_temp/temp_aweek_s, clear
		save ${outputdir}/EVENT_temp/07_aggdata_aweek_stkt`i', replace
		keep if (trigsever`i'==1 | trigsever`i'==2) & oldthreshticket`i'==1 & sampledriver`i'==1
		*** Collapse the dataset by weeks around ticket i
		*** simply keep the variables of interest and then drop duplicates		
		keep weeks_ticket`i' aweek_s*tkt`i'_speed aweek_s*tkt`i'_speedex aweek_s*tkt`i'_fspeeding aweek_s*tkt`i'_fspeedingex 		
		duplicates drop weeks_ticket`i' aweek_s*tkt`i'_speed, force
		sort weeks_ticket`i'

		save ${outputdir}/EVENT_temp/07_aggdata_aweek_stkt`i', replace
	}
	* end loop collapsing and saving datasets

	**************************************************************
	***PLOT THE GRAPHS, SEPARATELY BY SEVERITY, 
	*** with and without the trigger observation
	***************************************************************

	*** Loop by ticket (here, only 1st ticket)
	forvalues i = 1/1 {
		use ${outputdir}/EVENT_temp/07_aggdata_aweek_stkt`i', clear

		*** condition for the length of the time window around the ticket 
		global samplewindow "weeks_ticket`i'>=-prew & weeks_ticket`i'<=postw"

		* Loop by severity
		forvalues s = 1/1 {
			*** 32.3.1 Plot speeding measures
			* Figure D.1a
			* rate of speeding above limit	
			* ylabel(0.1 (0.05) 0.4)
			#delimit ;
			twoway (connect  aweek_s`s'tkt`i'_fspeeding weeks_ticket`i' , msymbol(O) msize(2.5))
			(connect aweek_s`s'tkt`i'_fspeedingex weeks_ticket`i', msymbol(T) msize(2.1)) if ${samplewindow}, 
			xline(0) xlabel(-${prew} (2) ${postw}) 
			ysc(r(0.1 0.4))
			ylabel(0 (0.05) 0.4)
			ytitle("speeding rate" "(share of drive-throughs above the speed limit )" " ")
			legend(label(1 "Including trigger observation") label(2 "Excluding trigger observation") size(small)) ;
			#delimit cr
			graph export ${outputdir}/EVENT_FIG/Fig_D1a_weeks_s`s'tkt`i'_fspeeding.png, replace width(1400)

			* Figure D.1b
			*** average speed		
			#delimit ;
			twoway (connect aweek_s`s'tkt`i'_speed weeks_ticket`i', msymbol(O) msize(2.5))	
			(connect aweek_s`s'tkt`i'_speedex weeks_ticket`i', msymbol(T) msize(2.1)) if ${samplewindow}, 
			xline(0) xlabel(-${prew} (2) ${postw}) 
			ysc(r(-5.5 -1))
			ylabel(-6 (1) -1)
			ytitle("average speed" "(km/h, difference from the speed limit)" " ")
			legend(label(1 "Including trigger observation") label(2 "Excluding trigger observation") size(small)) ;
			#delimit cr
			graph export ${outputdir}/EVENT_FIG/Fig_D1b_weeks_s`s'tkt`i'_speed.png, replace width(1400)

		} 
		*** end loop by severity
	}
	* end loop plotting graphs by ticket number
	*****************************************************
	capture erase ${outputdir}/EVENT_temp/temp_aweek_s.dta
	capture erase ${outputdir}/EVENT_temp/07_aggdata_aweek_stkt`i'.dta

}
* end sw07

****************************************************
*** Switch 8
*** REGRESSIONS - ROBUSTNESS CHECKS - DIFFERENT SAMPLE COMPOSITIONS
*** RESTRICTING THE SAMPLE ON SEVERAL CONDITIONS ON A SUFFICIENT NUMBER OF OBS BEFORE THE TICKET
*** Produces the following: 
*** Table D.1 (Event analysis: Sample composition: Speeding)
*** Table D.2 (Table D.2: Event analysis: Sample composition: Speed)
****************************************************
if `sw08_robchecksampleBE' == 1 {
	log using ${outputdir}/EVENT_TAB/08_log_robcheck_samplecarBE, replace
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear

	****************************************************
	*** ROBUSTNESS CHECK - SAMPLE COMPOSITION - CONDITIONING ON OBSERVATIONS BEFORE TICKET
	****************************************************
	*** Estimate the very basic regression (same as sw01)
	*** on different notions of subesample
	*** the samples are defined through variables samplecar*
	*** restrictions only on observations before (samplecar8be`i', samplecar6wbe`i', etc)
	*** these categories are mutually exclusive 0 - the sample split then covers all cars
	*** limit the analyiss only to the first ticket and severity 1
	*** all regs exclude the trigger obs
	*** outcomes:speeding and speed

	*** Loop over tickets(1st ticket only)
	forvalues i = 1 / 1 {
		*** Loop by the severity levels (low-fine only)
		forvalues s = 1/1 {
			************************************************
			***  Preparing for regressions
			*************************************************
			*** Variable lists and options - same as in sw01
			global Tdumprelist "dw_${prew1}_ticket`i'-dw_1_ticket`i'"
			global Tdumpostlist "dw1_ticket`i'-dw${postw}_ticket`i'"

			global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
			global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

			** outreg options, with different decimal points for different outcomes
			global outregspeeding "tex label dec(3)"
			global outregspeed    "tex label dec(2)"
			global addedtext_fe "car fe, yes, radar fe, yes, hour/day/month fe, radar-spec, traffic controls, radar-spec, weather controls, yes"

			** common sample condition: will add additional sample conditions
			global samplecondition "trigsever`i'==`s' & weeks_ticket`i'>=-prew1 & weeks_ticket`i'<=postw & oldthreshticket`i'==1 & sampledriver`i'==1"

			*** List of variables defining the subsamples
			*** all start with `samplecar' an end with ticket order, so use just the stubs
			*** Each of these also indicates a columns in the table
			global besamplestublist "2b 8be 999be 2wb 6wbe 999wbe"

			** Set omitted categories for dummies		
			* radar: //Ricanska-valley (the most frequent, and most violating)
			char radarid[omit] 5 
			* day of week: //Monday
			char dofweek[omit] 1 
			* hour of day: //7:00-7:59 am, morning rush hour
			char hofday[omit]  7
			* month of year: January (1st, slow traffic) 
			char mofyear[omit] 1 // January
			* schoolday: no school
			char schoolday[omit] 0 
			* holiday: //no holiday
			char holiday[omit] 0 
			* time difference from car in front: 0-2 seconds (bumper-to-bumper)
			char timediffint[omit] 2 

			*************************************
			*** 8.1  By alternative before-condition-only samples: speeding regressions 
			*************************************

			*** Loop over various subsamples:
			foreach stub of global besamplestublist {

				*******************************************************************
				*** Collect outcome averages pre-ticket
				*** and number of obs before/after
				******************************************************************
				* speeding,
				sum speeding if tkt_order~=`i' & samplecar`stub'`i'==1 & ${samplecondition} 
				local pt_speedingex = round(r(mean), 0.001)

				***************************************************
				*** Actual Regressions:
				***************************************************

				display "Outcome: speeding above the limit, ticket = `i', severity = `s'"
				display "Samplecar: `stub'"
				*** Table D.1, columns 1-6 (each `stub') constitutes a columns
				reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & samplecar`stub'`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
				sum speeding if e(sample) & dum_posttkt`i'==0
				local n_pre = r(N)
				sum speeding if e(sample) & dum_posttkt`i'==1
				local n_post = r(N)
				
				* for plotting the coefficients, save the estimates which will then be merged with the estimates for the Corporation
				parmest, saving(${outputdir}/EVENT_temp/temp_speeding_`stub'_tkt`i'_s`s', replace)
			}

			*** Combine the estimated coeffs into one file
			*** first, create a  variable indicating the samplecar
			foreach stub of global besamplestublist {
				use ${outputdir}/EVENT_temp/temp_speeding_`stub'_tkt`i'_s`s', clear
				gen samplecar = "`stub'"
				order samplecar, first
				save ${outputdir}/EVENT_temp/temp_speeding_`stub'_tkt`i'_s`s', replace
			}

			*** Second, append them together
			local nsamples: word count ${besamplestublist} 
			local 1stub : word 1 of ${besamplestublist}
			use ${outputdir}/EVENT_temp/temp_speeding_`1stub'_tkt`i'_s`s'
			forvalues c = 2/`nsamples' {
				local stub : word `c' of ${besamplestublist}
				append using ${outputdir}/EVENT_temp/temp_speeding_`stub'_tkt`i'_s`s'
			}
			save ${outputdir}/EVENT_TAB/TabD1_coeffs_besamplecar_speeding_tkt`i'_s`s', replace
			foreach stub of global besamplestublist {
				erase ${outputdir}/EVENT_temp/temp_speeding_`stub'_tkt`i'_s`s'.dta
			}
			use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear


			*************************************
			*** 8.2. By alternative before-condition-only samples: speed regressions 
			*************************************
			
			*** Loop over various subsamples:
			foreach stub of global besamplestublist {

				*******************************************************************
				*** Collect outcome averages pre-ticket
				******************************************************************
				* speeding,
				sum speedm if tkt_order~=`i' & samplecar`stub'`i'==1 & ${samplecondition} 
				local pt_speedex = round(r(mean), 0.01)

				***************************************************
				*** Actual Regressions:
				***************************************************

				display "Outcome: speed (difference from speed limit), ticket = `i', severity = `s'"
				display "Samplecar: `stub'"

				*** Table D.2, columns 1-6 (each `stub') constitutes a columns
				reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & samplecar`stub'`i'==1 & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
				sum relspeedm if e(sample) & dum_posttkt`i'==0
				local n_pre = r(N)
				sum relspeedm if e(sample) & dum_posttkt`i'==1
				local n_post = r(N)	
				
				* for plotting the coefficients, save the estimates which will then be merged with the estimates for the Corporation
				parmest, saving(${outputdir}/EVENT_temp/temp_speed_`stub'_tkt`i'_s`s', replace)
			}

			*** Combine the estimated coeffs into one file
			*** first, create a  variable indicating the samplecar
			foreach stub of global besamplestublist {
				use ${outputdir}/EVENT_temp/temp_speed_`stub'_tkt`i'_s`s', clear
				gen samplecar = "`stub'"
				order samplecar, first
				save ${outputdir}/EVENT_temp/temp_speed_`stub'_tkt`i'_s`s', replace
			}

			*** Second, append them together
			local nsamples: word count ${besamplestublist} 
			local 1stub : word 1 of ${besamplestublist}
			use ${outputdir}/EVENT_temp/temp_speed_`1stub'_tkt`i'_s`s'
			forvalues c = 2/`nsamples' {
				local stub : word `c' of ${besamplestublist}
				append using ${outputdir}/EVENT_temp/temp_speed_`stub'_tkt`i'_s`s'
			}
			save ${outputdir}/EVENT_TAB/TabD2_coeffs_besamplecar_speed_tkt`i'_s`s', replace
			foreach stub of global besamplestublist {
				erase ${outputdir}/EVENT_temp/temp_speed_`stub'_tkt`i'_s`s'.dta
			}
			use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear

		}
		* end loop over severity
	}
	* end loop over ticket
	log close
}
* end switch sw08

****************************************************
*** Switch 9
*** REGRESSIONS - RESPONSES TO 2ND TICKET
*** SAMPLE RESTRICTED TO DRIVERS WHOSE FIRST TICKET WAS OF LOW SEVERITY
	
*** Produces the following: 
*** Figure A.18 (Event study estimates for responses to the second ticket)
*** Table A.13, col 5-6 (Event study estimates for responses to the second ticket: Second ticket re-offence)
****************************************************
if `sw09_2ndadditional' == 1 {
	log using ${outputdir}/EVENT_TAB/09_log_2ndadditional, replace
	*************************************************************************************
	*** RESPONSE TO THE 2ND TICKET
	*** SAMPLE RESTRICTED TO DRIVERS WHOSE FIRST TICKET WAS OF LOW SEVERITY
	
	*************************************************************************************
	use ${datadir}/Dusek_Traxler_EVENT_weekeffects, clear
	***********************************
	*** Preparing the regressions
	***********************************
	*** List of treatment dummies in the order we want it, with week zero as ommitted category
	* The pre/post dummies run around ticket 2
	global Tdumprelist "dw_${prew1}_ticket2-dw_1_ticket2"
	global Tdumpostlist "dw1_ticket2-dw${postw}_ticket2"

	* time and traffic controls: everyting radar-specific
	global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
	global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

	*** General condition for the sample - time window and sampledriver
	*** Crucial: Time window around 2nd ticket, but the 1st ticket severity was of low severity
	global samplecondition "trigsever1==1 & weeks_ticket2>=-${prew1} & weeks_ticket2<=${postw} & oldthreshticket2==1 & sampledriver2==1"
	*** general options for outreg
	global outregspeeding "tex label dec(3) drop(_I*)"
	global outregspeed    "tex label dec(2) drop(_I*)"

	*** Text for the note - different for regs without/with driver f.e.
	global addedtext_fe "car fe, yes, zone fe, yes, hofd/dofw/mofy fe, zone-spec, traffic controls, zone-spec, weather controls, yes"

	** Set omitted categories for dummies
	* radar: //Ricanska-valley (the most frequent, and most violating)
	char radarid[omit] 5 
	* day of week: //Monday
	char dofweek[omit] 1 
	* hour of day: //7:00-7:59 am, morning rush hour
	char hofday[omit]  7
	* month of year: January (1st, slow traffic) 
	char mofyear[omit] 1 // January
	* schoolday: no school
	char schoolday[omit] 0 
	* holiday: //no holiday
	char holiday[omit] 0 
	* time difference from car in front: 0-2 seconds (bumper-to-bumper)
	char timediffint[omit] 2 

	*** Defining the heterogeneity groups same way as in sw37
	*** Median of this value for those who committed the 2nd offense after 1st ticket and not between 1st offense and ticket)
	sum gap_offatkt1 if tkt_order==1 & trigsever1==1 & oldthreshticket1==1 & sampledriver1==1 & d_offafter_tkt1~=. & d_offafter_tkt1==d_offafter_off1, detail
	display "The median gap bw 2nd offense and tkt1 is: "
	display r(p50)
	scalar medgap = r(p50)

	*** Three groups: 
	*** 1. reoffended after 1st offense for the 1st time after 1st ticket, small gap from 1st ticket
	*** 2. reoffended after 1st offense for the 1st time after 1st ticket, large gap from 1st ticket
	*** 3. never offended after 1st offense

	*** define the criteria for these groups (other than the general sample condition
	* groups 1 and 2: technically: day when offended first after 1st ticket is the same as offending first after 1st offense
	global group1 "d_offafter_tkt1~=. & d_offafter_tkt1==d_offafter_off1 & gap_offatkt1<=medgap"
	global group2 "d_offafter_tkt1~=. & d_offafter_tkt1==d_offafter_off1 & gap_offatkt1>medgap"
	global group3 "d_offafter_off1==."

	*****************************************************************
	*** 9.1. RESPONSE TO 2ND TICKET OVERALL FOR ALL 2ND OFFENDERS
	*****************************************************************
	* Erase outfiles: 
	capture erase ${outputdir}/EVENT_TAB/TabA13_2ndtktall_c5_c6_s11tkt2.txt
	capture erase ${outputdir}/EVENT_TAB/TabA13_2ndtktall_c5_c6_s11tkt2.tex

	*** 9.1.1  Regressions with all reoffenders (group 1 and 2): speeding 

	*** All regressions exclude the trigger obs
	* Collect pre-ticket (that is, pre-2nd ticket) averages

	sum speeding if tkt_order~=2 & weeks_ticket2==0 & (${group1} | ${group2}) & ${samplecondition} 
	local pt_speeding = round(r(mean), 0.001)

	display "Response after the 2nd ticket, for those who did not commit the 2nd offense before 1st ticket"
	display "Outcome: speeding above the limit"
	* Figure A.18a, Table A.13 col 5
	display "Speeding, groups 1 and 2"
	reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if (${group1} | ${group2}) & tkt_order~=2 & ${samplecondition}, vce(cluster id radarid#day#hofday) absorb(id)
	outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA13_2ndtktall_c5_c6_s11tkt2, ${outregspeeding} ctitle(speeding, 1st tkt severity 1) addtext(pre-ticket mean, `pt_speeding', no. of cars, `e(N_clust)', ${addedtext_fe}) append
	* store estimates for plotting
	parmest, saving(${outputdir}/EVENT_FIG/parms, replace)
	* Figure A.18a
	** plot the coefficients into one graph (with / without CI)
	plotRegWeeks "Fig_A18a_coefplot_2ndtktall_speeding_s11tkt2" "" "Probability of speeding" "" "Weeks before/after ticket 2" ""

	*** Regressions with all reoffenders (group 1 and 2): speed

	*** All regressions exclude the trigger obs
	* Collect pre-ticket averages

	sum speedm if tkt_order~=2 & weeks_ticket2==0 & (${group1} | ${group2}) & ${samplecondition} 
	local pt_speedm = round(r(mean), 0.001)

	display "Response after the 2nd ticket, for those who did not commit the 2nd offense before 1st ticket"
	display "Outcome: speeding above the limit"
	* Figure A.18b, Table A.13 col 6
	display "Speed, groups 1 and 2"
	reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if (${group1} | ${group2}) & tkt_order~=2 & ${samplecondition}, vce(cluster id radarid#day#hofday) absorb(id)
	outreg2 ${Tdumprelist} ${Tdumpostlist} using ${outputdir}/EVENT_TAB/TabA13_2ndtktall_c5_c6_s11tkt2, ${outregspeed} ctitle(speed, 1st tkt severity 1) addtext(pre-ticket mean, `pt_speedm', no. of cars, `e(N_clust)', ${addedtext_fe}) append
	* store estimates for plotting
	parmest, saving(${outputdir}/EVENT_FIG/parms, replace)
	* JEEA Figure A.18b
	** plot the coefficients into one graph (with / without CI)
	plotRegWeeks "Fig_A18b_2ndtktall_speed_s11tkt2" "" "Speed (km/h)" "" "Weeks before/after ticket 2" ""

	log close
}
* end switch 09


**********************************************
******************************************
*** MONTHLY LONG RUN EFFECTS ************
******************************************
*******************************************
*** EVENT ANALYSIS - AROUND THE TIME OF GETTING THE TICKET
*** ANALYSIS WITH MONTHLY EFFECTS, LONG-WINDOW OUTCOME

*** Set the length of pre-post windows as parameter scalars
*** both global macro (for dummy titles etc) and scalar for computations 
** windows in terms of weeks - may need to adjust with version!
global prem "6"
global postm "24"
local prem = ${prem}
scalar prem =  ${prem}
local postm = ${postm}
scalar postm = ${postm}
* also need # of pre-months -1
scalar prem1 = prem - 1
local prem1 = `prem' - 1
global prem1 "`prem1'"

********************************************************
*** Switch 10
*** BASIC REGRESSIONS - TIME AROUND THE TICKET,
*** LONG-RUN RESPONSES (MONTHLY EFFECTS) 
*** Produces the following: 
*** Figure 7 (Event study estimates: long-run effects)
*** Table A.11, col 1,2 (Event analysis: long-run effects, analysis by the order of rides: long run effects)
********************************************************
if `sw51_regsbasic' == 1 {
	log using ${outputdir}/EVENT_TAB/10_log_eventmonths, replace
	use ${datadir}/Dusek_Traxler_EVENT_montheffects
	**********************************************
	**** 10. REGRESSIONS - BASIC EVENT ANALYSIS AROUND THE TICKET
	************************************************

	*** Outfiles:
	*** for the paper appendix: one table for both tickets, speed and speeding
	* preferred spec: all controls, exclude trigger

	* Erase existing outfiles: to save lines, do this in a loop over file names	
		capture erase ${outputdir}/EVENT_TAB/TabA11_monthregs_c1_c2.txt
		capture erase ${outputdir}/EVENT_TAB/TabA11_monthregs_c1_c2.tex		
		
	*** Loop by the ticket order
	forvalues i = 1/1 {
		***********************************
		*** 10.0 Preparing the regressions
		***********************************
		*** List of treatment dummies in the order we want it, with week zero as ommitted category
		* treatments are defined with each ticket, but we need to run the regs with the T variables without `i'
		* create proxy variables dm*`j'reg 
		scalar prem1 = prem -1 
		local prem1 = prem1
		forvalues j =  `prem1' (-1) 1  {
			rename dm_`j'_ticket`i' dm_`j'_reg
		}

		forvalues j = 0 (1) ${postm} {
			rename dm`j'_ticket`i' dm`j'_reg
		}
		
		global Tdumprelist "dm_${prem1}_reg-dm_1_reg"
		global Tdumpostlist "dm1_reg -dm${postm}_reg"

		* time, traffic, and weather controls: everyting radar-specific
		global Xlist "radarid##dofweek radarid##hofday radarid##mofyear radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
		global Xlistmonth "radarid##dofweek radarid##hofday radarid##month radarid##schoolday radarid##holiday radarid##timediffint radarid##c.ncars_rdh"
		global Wlist "temprt_p* dum_precipzero precip_p* solar_p* wind_p*"

		*** General condition for the sample - time window and sampledriver
		global samplecondition "months_ticket`i'>=-${prem1} & months_ticket`i'<=${postm} & oldthreshticket`i'==1 & sampledriver`i'==1"
		*** general options for outreg
		global outregspeeding "tex label dec(3)"
		global outregspeed    "tex label dec(2)"

		*** Text for the note - different for regs without/with driver f.e.
		global addedtext_fe "car fe, yes, radar fe, yes, hofd/dofw/mofy fe, radar-spec, traffic controls, radar-spec"

		** Set omitted categories for dummies
		* radar: //Ricanska-valley (the most frequent, and most violating)
		char radarid[omit] 5 
		* day of week: //Monday
		char dofweek[omit] 1 
		* hour of day: //7:00-7:59 am, morning rush hour
		char hofday[omit]  7
		* month of year: January (1st, slow traffic) 
		char mofyear[omit] 1 // January
		* schoolday: no school
		char schoolday[omit] 0 
		* holiday: //no holiday
		char holiday[omit] 0 
		* time difference from car in front: 0-2 seconds (bumper-to-bumper)
		char timediffint[omit] 2 
	
		*********************************************************
		*** 10.1. OUTCOME: Speeding, pre-post dummies
		*****************************************************************
		
		display "Speeding after ticket, Ticket order = `i'"
		display "Driver F.E., pre-and post-ticket dummies, excl. trigger obs"
		
		*** compute the pre-treatment mean of the outcome and include in the regression output
		sum speeding if tkt_order~=`i' & months_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pretreat0ex = round(r(mean), 0.001) 
		
		* Figure A.7a, Table A.11 Col 1
		xi: reghdfe speeding ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
		outreg2 using ${outputdir}/EVENT_TAB/TabA11_monthregs_c1_c2, $outregspeeding keep(dm*reg) ctitle(ticket`i', speeding) addtext(pre-ticket mean, `pretreat0ex', no. of cars, `e(N_clust)', ${addedtext_fe}, weather controls, yes) 

		* Figure A.7a
		parmest, saving(${outputdir}/EVENT_FIG/parms, replace)		
		plotRegMonths "Fig_7a_coefplotmonth_speeding_excltrig_tkt`i'" "" "Probability of speeding" "" "Months before/after ticket `i'" ""

		*********************************************************
		*** 10.2. OUTCOME: Speed, pre-post dummies
		********************************************************************
		
		display "Rel speed after ticket, Ticket order = `i'"
		display "Driver F.E., pre-and post-ticket dummies, excl. trigger obs"
	
		*** compute the pre-treatment mean of the outcome and include in the regression output
		sum speedm if tkt_order~=`i' & months_ticket`i'==0 & oldthreshticket`i'==1 & sampledriver`i'==1
		local pretreat0ex = round(r(mean), 0.001) 
		
		* Figure A.7b, Table A.11 Col 2
		xi: reghdfe relspeedm ${Tdumprelist} ${Tdumpostlist} ${Xlist} ${Wlist} if tkt_order~=`i' & $samplecondition, vce(cluster id radarid#day#hofday) absorb(id)
		outreg2 using ${outputdir}/EVENT_TAB/TabA11_monthregs_c1_c2, $outregspeeding keep(dm*reg) ctitle(ticket`i', speed) addtext(pre-ticket mean, `pretreat0ex', no. of cars, `e(N_clust)', ${addedtext_fe}, weather controls, yes) 
		
		* Figure A.7b
		parmest, saving(${outputdir}/EVENT_FIG/parms, replace)
		plotRegMonths "Fig_7b_coefplotmonth_speed_excltrig_tkt`i'" "" "Speed (km/h)" "" "Months before/after ticket `i'" ""	

	}
	* end of loop over tickets
	log close
}
* end switch 10

*** Erase auxilary files and temp files
capture erase ${outputdir}/EVENT_temp/temp
capture erase scheme-new.scheme
